<?php

class Grupos extends Onecore_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model("grupos_model");
        $this->_moduleName = utf8_encode("Administración de Grupos");
        $this->_moduleDescription = utf8_encode("Description") . $this->_moduleName;
        $this->_modelInstance = $this->grupos_model;
    }
    public function requestCreate() {
        $this->load->model("walls_model");
        $this->load->model('posts_model');
        $success = false;
        
        $this->form_validation->set_rules($this->_modelInstance->getValidations());
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = "Solicitud ingresada en forma exitosa";
        $errorList = array();
        $edit = false;
        $groupId = "-1";
        
        if ($this->session){
            $this->load->model('tipogrupos_model');
            $this->load->model('tiporols_model');
            $this->load->model('rols_model');
            $this->load->model('users_model');
            $this->load->model('requests_model');
            
            $uid  =  $this->session->userdata('uid');
            $rolUser  =  $this->session->userdata('id_perfil');
            $rolNeedValidation = $this->config->item('rol_need_validation');
            
            $user = $this->users_model->getByUserId($uid);
            $user = $user[0];
            $username = $user->nombre1.' '.$user->apellido1;

            $gid       = $this->tipogrupos_model->getBynombre('celula');
            $rol_id    = $this->tiporols_model->getBynombrerol('lider');
            $TipoGrupoId       = $gid[0]->TipoGrupoId;
            $TipoRolId    = $rol_id[0]->TipoRolId;
            
            if(in_array($rolUser, $rolNeedValidation)){
                

                $gen  = $this->users_model->get_user_geneaology($uid,$username,$TipoRolId,$TipoGrupoId);

                //print_r($gen);

                $uidReceive = "";
                foreach($gen as $userTree){
                    if(!empty($userTree['SystemRolId']) && $userTree['SystemRolId'] === 'lider_12_principal'){
                        $uidReceive = $userTree['user'];
                    // echo $uidReceive;
                        break;
                    }
                }
                //si es rol que necesita validacion lo vemos
                if ($this->form_validation->run() == FALSE) {
                $mensaje = "Campos inválidos";
                $errorList = $this->form_validation->_error_array;
                } 
                else {
                    $this->db->trans_begin();
                    $data = array(
                        "id" => "",
                        "data" => $this->getInputsToSave($this->input->post(), $this->_modelInstance->getFields())
                    );
                    $data['data']['estado'] = 'requiere_aprobacion';
                    if ($this->_modelInstance->save($data, false)) {
                        $groupId = $this->_modelInstance->getLastInsertedId();
                        $dataWall = array(
                            "id" => "",
                            "data" => array(
                                'Title'=>'Muro de '.$this->input->post('nombre'),
                                'GrupoId'=>$groupId
                            )
                        );
                        if ($this->walls_model->save($dataWall, false)) {
                            $dataPost = array(
                                "data" => array(
                                    'UserId'=>$uid,
                                    'WallId'=>$this->walls_model->getLastInsertedId(),
                                    'Created'=>date('Y-m-d'),
                                    'Message'=>'Bienvenido al Grupo '.$this->input->post('nombre'),
                                    
                                )
                            );
                            if ($this->posts_model->save($dataPost, false)) {
                                $dataRol = array(
                                    "id" => "",
                                    "data" => array(
                                        'UserId'=>$uid,
                                        'TipoRolId'=>$TipoRolId,
                                        'GrupoId'=>$groupId
                                    )
                                );
                                if ($this->rols_model->save($dataRol, false)) {
                                    $dataReq = array(
                                        "id" => "",
                                        "data" => array(
                                            'UserIdSend'=>$uid,
                                            'UserIdReceive'=>$uidReceive,
                                            'Data'=>json_encode(array('GrupoId'=>$groupId)),
                                            'Type'=>'solicitud_crear_grupo',
                                            'Messages'=>$this->input->post('observacion')
                                        )
                                    );
                                    if ($this->requests_model->save($dataReq, false)) {
                                        $success = true;
                                    }
                                    else{
                                        $mensaje = "La solicitud no pudo ser creada.";
                                        $errorList = array("Error" => $this->requests_model->getError());
                                    }
                                }
                                else{
                                    $mensaje = "El rol no pudo ser creado.";
                                    $errorList = array("Error" => $this->rols_model->getError());
                                }
                            }
                            else{
                                $mensaje = "El " . $itemName . " no pudo ser guardado. Error al crear el mensaje de bienvenida.";
                                $errorList = array("Error" => $this->posts_model->getError());
                            }
                        }
                        else{
                            $mensaje = "El " . $itemName . " no pudo ser guardado. Error al crear el muro.";
                            $errorList = array("Error" => $this->walls_model->getError());
                        }

                    } else {
                        $mensaje = "El " . $itemName . " no pudo ser guardado. Verifique los siguientes errores.";
                        $errorList = array("Error" => $this->_modelInstance->getError());
                    }
                    if ($success) {
                        $this->db->trans_commit();
                    } else {
                        $this->db->trans_rollback();
                    }
                }
            }//en caso contrario creamos el grupo normalmente y agregamos el rol lider con el usuario logueado
            else{
                
                $this->db->trans_begin();
                $data = array(
                    "id" => "",
                    "data" => $this->getInputsToSave($this->input->post(), $this->_modelInstance->getFields())
                );
                if ($this->_modelInstance->save($data, false)) {
                    $groupId = $this->_modelInstance->getLastInsertedId();
                    $dataWall = array(
                        "id" => "",
                        "data" => array(
                            'Title'=>'Muro de '.$this->input->post('nombre'),
                            'GrupoId'=>$groupId
                        )
                    );
                    if ($this->walls_model->save($dataWall, false)) {
                        $dataPost = array(
                            "data" => array(
                                'UserId'=>$uid,
                                'WallId'=>$this->walls_model->getLastInsertedId(),
                                'Created'=>date('Y-m-d'),
                                'Message'=>'Bienvenido al Grupo '.$this->input->post('nombre'),

                            )
                        );
                        if ($this->posts_model->save($dataPost, false)) {
                            $dataRol = array(
                                "id" => "",
                                "data" => array(
                                    'UserId'=>$uid,
                                    'TipoRolId'=>$TipoRolId,
                                    'GrupoId'=>$groupId
                                )
                            );
                            if ($this->rols_model->save($dataRol, false)) {
                                $mensaje = "Grupo creado en forma exitosa";
                                $success = true;
                            }
                            else{
                                $mensaje = "El " . $itemName . " no pudo ser guardado. Error al asociar su cuenta como lider al grupo..";
                                $errorList = array("Error" => $this->rols_model->getError());
                            }
                        }
                        else{
                            $mensaje = "El " . $itemName . " no pudo ser guardado. Error al crear el mensaje de bienvenida.";
                            $errorList = array("Error" => $this->posts_model->getError());
                        }
                    }
                    else{
                        $mensaje = "El " . $itemName . " no pudo ser guardado. Error al crear el muro.";
                        $errorList = array("Error" => $this->walls_model->getError());
                    }

                } else {
                    $mensaje = "El " . $itemName . " no pudo ser guardado. Verifique los siguientes errores.";
                    $errorList = array("Error" => $this->_modelInstance->getError());
                }
                if ($success) {
                    $this->db->trans_commit();
                } else {
                    $this->db->trans_rollback();
                }
            }
        }
        else{
            $mensaje = "Debe estar logueado para completar esta operación.";
            $errorList = array("Error" => "Debe estar logueado para completar esta operación.");
        }
        
        $res = array(
            "success" => $success,
            "msg" => $mensaje,
            "errors" => $errorList,
            'data'=>array(
                'GrupoId'=>$groupId
            )
        );
        $this->layout->printLike(json_encode($res), "json");
    }
    public function add() {
        $this->load->model("walls_model");
        $success = false;
        $this->form_validation->set_rules($this->_modelInstance->getValidations());
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = $itemName . " ingresado en forma exitosa";
        $errorList = array();
        $edit = false;
        

        if ($this->form_validation->run() == FALSE) {
            $mensaje = "Campos inválidos";
            $errorList = $this->form_validation->_error_array;
        } else {
            $this->db->trans_begin();
            $data = array(
                "id" => "",
                "data" => $this->getInputsToSave($this->input->post(), $this->_modelInstance->getFields())
            );

            if ($this->_modelInstance->save($data, false)) {
                $dataWall = array(
                    "id" => "",
                    "data" => array(
                        'Title'=>'Muro de '.$this->input->post('nombre'),
                        'GrupoId'=>$this->_modelInstance->getLastInsertedId()
                    )
                );
                if ($this->walls_model->save($dataWall, false)) {
                    $success = true;
                }
                else{
                    $mensaje = "El " . $itemName . " no pudo ser guardado. Error al crear el muro.";
                    $errorList = array("Error" => $this->walls_model->getError());
                }
                
            } else {
                $mensaje = "El " . $itemName . " no pudo ser guardado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->_modelInstance->getError());
            }
            if ($success) {
                $this->db->trans_commit();
            } else {
                $this->db->trans_rollback();
            }
        }
        $res = array(
            "success" => $success,
            "msg" => $mensaje,
            "errors" => $errorList
        );
        $this->layout->printLike(json_encode($res), "json");
    }

    public function edit() {
        $success = false;
        $this->form_validation->set_rules($this->_modelInstance->getValidations());
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = $itemName . " editado en forma exitosa";
        $errorList = array();
        $edit = false;

        if ($this->form_validation->run() == FALSE) {
            $mensaje = "Campos inválidos";
            $errorList = $this->form_validation->_error_array;
        } else {
            $this->db->trans_begin();
            $data = array(
                "id" => $this->getFilterFieldsToEdit($this->input->post(), $this->_modelInstance->getFields()),
                "data" => $this->getInputsToSave($this->input->post(), $this->_modelInstance->getFields())
            );
            if ($this->_modelInstance->save($data, true)) {
                $success = true;
            } else {
                $mensaje = "El " . $itemName . " no pudo ser guardado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->_modelInstance->getError());
            }
            if ($success) {
                $this->db->trans_commit();
            } else {
                $this->db->trans_rollback();
            }
        }
        $res = array(
            "success" => $success,
            "msg" => $mensaje,
            "errors" => $errorList
        );
        $this->layout->printLike(json_encode($res), "json");
    }

    public function del() {
        $itemName = $this->_modelInstance->getItemName();
        $success = false;
        $mensaje = "El " . $itemName . " seleccionado no pudo ser eliminado";
        $errorList = array();
        $data = array(
            "id" => $this->getInputsToSave($this->input->post(), $this->_modelInstance->getFields())
        );
        $this->db->trans_begin();
        if ($this->_modelInstance->del($data)) {
            $success = true;
        } else {
            $errorList = array("Error" => $this->_modelInstance->getError());
        }
        if ($success) {
            $mensaje = $itemName . " eliminado en forma exitosa";
            $this->db->trans_commit();
        } else {
            $this->db->trans_rollback();
        }
        $res = array(
            "success" => $success,
            "msg" => $mensaje,
            "errors" => $errorList
        );
        $this->layout->printLike(json_encode($res), "json");
    }

    public function index() {
        $banner["module_name"] = $this->_moduleName;
        $banner["module_description"] = $this->_moduleDescription;
        $data["module_banner"] = $this->load->view("/include/sections/module_banner/module_title", $banner, true);
        $data["page_title"] = "Administración de Grupos";
        $this->layout->view("/grupos/index", $data);
    }

    public function user_groups()
    {
                $banner["module_name"] = 'Usuarios y grupos';
                $banner["module_description"] = 'Gestion de usuarios y grupos';
                $data["module_banner"] = $this->load->view("/include/sections/module_banner/module_title",$banner,true);
                $data["page_title"] = "Administración de Grupos";
                $data["group_id"] = $this->input->get('group_id');
                $data["group_data"] = $this->_modelInstance->get_data_group($data["group_id"]);
                $data["leader_data"] = $this->_modelInstance->get_leader_data($data["group_id"]);
                
                $this->layout->view("/grupos/user_groups",$data);
    }

    public function mis_grupos() {
        $banner["module_name"] = 'Mis Grupos';
        $banner["module_description"] = 'Grupos que administro';
        $data["module_banner"] = $this->load->view("/include/sections/module_banner/module_title", $banner, true);
        $data["page_title"] = "Participo en";
        
        $data["UserId"] = $this->session->userdata('uid');
        
        $this->layout->view("/grupos/mygroups", $data);
    }
    public function participo_en() {
        $banner["module_name"] = 'Participo en';
        $banner["module_description"] = 'Grupos en los que participo';
        $data["module_banner"] = $this->load->view("/include/sections/module_banner/module_title", $banner, true);
        $data["page_title"] = "Participo en";
        $this->layout->view("/grupos/participe", $data);
    }
    public function getGroups(){
        $rolesMembers = $this->config->item('roles_miembros');
        $rolesLideres = $this->config->item('roles_lideres');
        $this->load->model("rols_model");
        $roles = $rolesLideres;
        $success = false;
        $mensaje = "Error al traer grupos del usuario.";
        $typeRol = $this->input->post("type");
        $rp_members = $this->input->post("rp_members");
        $res = array();
        if ($this->session){
            $mensaje = "todo ok";
            if(in_array($typeRol, $rolesMembers))
                $roles = $rolesMembers;
            $uid  =  $this->session->userdata('uid');
            $res = $this->_modelInstance->getGroupsByUser($uid,$roles,$rp_members);
        }
        $data = array(
            "success"=>$success,
            "data"=>$res,
            "msg"=>$mensaje,
        );
        $this->layout->printLike(json_encode($data),"json");
    }
    
    
    public function loadGrid() {
        $conditions = array();
        $page = $this->input->post("page");
        $rp = $this->input->post("rp");

        $sort = $this->input->post("sortname");
        $dir = $this->input->post("sortorder");

        $query = $this->input->post("query");
        $qtype = $this->input->post("qtype");

        if (!empty($query) && $query !== "null") {
            $obj = array($qtype => $query);
            $fields = $this->_modelInstance->getFields();
            $conditionsFields = $this->_modelInstance->getFieldsConditions();
            $conditions = $this->getConditionsByObject($obj, $conditionsFields, $fields);
            if ($qtype == 'Sector')
                array_push($conditions, array('field' => 'tbl_sectors.nombre', 'value' => $query, 'type' => 'like'));
            if ($qtype == 'TipoGrupo')
                array_push($conditions, array('field' => 'tbl_tipogrupos.nombre', 'value' => $query, 'type' => 'like'));
            if ($qtype == 'Iglesia')
                array_push($conditions, array('field' => 'tbl_iglesias.nombre', 'value' => $query, 'type' => 'like'));
        }
        $order = null;
        if (!empty($sort) && $sort !== "null") {
            $obj = json_decode($sort);
            $order = array(
                "field" => $sort,
                "direction" => $dir
            );
        }

        $selected = array();
        $items = $this->_modelInstance->loadGrid($page, $rp, $conditions, $order, $selected);
        $data = array(
            "success" => true,
            "total" => $items["results"],
            "rows" => $items["items"],
            "page" => $items["page"]
        );
        $this->layout->printLike(json_encode($data), "json");
    }

    
    public function load_user_church()
    {
        $conditions=array();
                $page = $this->input->post("page");
        	$rp = $this->input->post("rp");
        
                $sort = $this->input->post("sortname");
                $dir = $this->input->post("sortorder");
        
                $query = $this->input->post("query");
                $qtype = $this->input->post("qtype");
                
                //$id_iglesia = $this->input->post("item");
                $id_iglesia = $this->input->post("IglesiaId");
                                
                
                $conditions = array();         
                if(!empty($query) && $query !== "null"){
                    array_push($conditions,array('field' => $qtype,'value' => $query,'type' => 'like'));
                }
                array_push($conditions,array('field' => 'tbl_grupos.IglesiaId','value' => $id_iglesia,'type' => 'where'));
                array_push($conditions,array('field' => 'tbl_tipogrupos.name','value' => 'congregacion','type' => 'where'));
                
                $order = null;
                if(!empty($sort) && $sort !== "null"){
                    $obj = json_decode($sort);
                    $order = array(
                        "field"=>$sort,
                        "direction"=>$dir
                    );
                }
        
                $selected = array();
                $items = $this->_modelInstance->load_user_church($page, $rp,$conditions,$order,$selected);
                $data = array(
                    "success"=>true,
                    "total"=>$items["results"],
                    "rows"=>$items["items"],
                    "page"=>$items["page"]
                );
                $this->layout->printLike(json_encode($data),"json");

    }

    public function loadUserGroup() {
        $conditions = array();
        $page = $this->input->post("page");
        $rp = $this->input->post("rp");

        $sort = $this->input->post("sortname");
        $dir = $this->input->post("sortorder");

        $query = $this->input->post("query");
        $qtype = $this->input->post("qtype");

        $grupoId = $this->input->post("GrupoId");



        $conditions = array();
        if(!empty($query) && $query !== "null"){
            if($qtype == 'sexo') array_push($conditions,array('field' => 'tbl_users.'.$qtype,'value' => $query,'type' => 'like'));
            if($qtype == 'direccion') array_push($conditions,array('field' => 'tbl_users.'.$qtype,'value' => $query,'type' => 'like'));
            if($qtype == 'nombre1') array_push($conditions,array('field' => 'tbl_users.'.$qtype,'value' => $query,'type' => 'like'));
            if($qtype == 'apellido1') array_push($conditions,array('field' => 'tbl_users.'.$qtype,'value' => $query,'type' => 'like'));
            if($qtype == 'rut') array_push($conditions,array('field' => 'tbl_users.'.$qtype,'value' => $query,'type' => 'like'));
            if($qtype == 'rol') array_push($conditions,array('field' => 'tbl_tiporols.nombrerol','value' => $query,'type' => 'like'));            
        }
        array_push($conditions, array('field' => 'tbl_rols.GrupoId', 'value' => $grupoId, 'type' => 'where'));
        
        $order = null;
        if (!empty($sort) && $sort !== "null") {
            $obj = json_decode($sort);
            $order = array(
                "field" => $sort,
                "direction" => $dir
            );
        }

        $selected = array();
        $items = $this->_modelInstance->loadUserGroup($page, $rp, $conditions, $order, $selected);
        $data = array(
            "success" => true,
            "total" => $items["results"],
            "rows" => $items["items"],
            "page" => $items["page"]
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    
    function getItem(){
        $selected = array();
        $conditions = array();
        $item = $this->input->post('item');
        $res = array();
        if(!empty($item) && $item !== ''){
            $obj = json_decode($item);
            $res = $this->_modelInstance->getItem($obj->GrupoId);
        }
        $data = array(
            'success'=>true,
            'data'=>$res
        );
        $this->layout->printLike(json_encode($data),'json');
    }
    
    public function get_data_group($group_id){
         
         $group_data  = $this->_modelInstance->get_data_group($group_id);
         $leader_data = $this->_modelInstance->get_leader_data($group_id);
         //$group_data[] = $leader_data;
         if(empty($leader_data)){
             $leader_data = array('username'=>'','fono'=>'','email'=>'');
         }
         foreach($leader_data as $ld){
             $group_data[] = $ld;
         }
         
         $data = array(
            'success'=>true,
            'data'=>$group_data
         );
         $this->layout->printLike(json_encode($data),'json');
    }
    public function delUserByRol(){
        $uid = $this->input->post('uid');
        $uid = explode('_',$uid);
        $errorlist = array();
        $this->load->model('rols_model');
        $this->load->model('tiporols_model');
        $this->load->model('tipogrupos_model');
        $this->load->model('grupos_model');
        
        $rols_data = $this->rols_model->getByGrupoId($uid[0]);
        $role_data = $this->tiporols_model->getBynombrerol('lider');
        $role_data = $role_data[0]->TipoRolId;
        $role;
        
        $tp = $this->tipogrupos_model->getByNameGrupo('congregacion');
        $tp = $tp[0];
        $grupo = $this->grupos_model->getByGrupoId($uid[0]);
        $grupo = $grupo[0];
        
        $session_id = $this->session->userdata('id_usuario');
        $uidSession = $this->session->userdata('uid');
        $mensaje = 'Error al remover al usuario del grupo';
        if($grupo->TipoGrupoId !== $tp->TipoGrupoId){
            $this->load->model("users_model");
            $user_data = $this->users_model->getByusername($session_id);
            $user_data = $user_data[0]->UserId;
            if($user_data !== $uid[1]){
                foreach($rols_data as $rd){
                    if($rd->UserId == $user_data) $role = $rd->TipoRolId;  
                }
                $success;
                $mensaje;

                if($role == $role_data){
                    //borra usuario
                    $flag = $this->_modelInstance->delUserByRol($uid[1],$uid[0]);
                    if($flag){
                        $success = true;
                        $errorlist = array('Error'=>'Operacion realizada exitosamente');
                    }
                    else{
                        $success = false;
                        $errorlist = array('Error'=>'Hubo un problema al realizar la operacion');
                    }
                }
                else
                {
                    $success = false;
                    $errorlist = array('Error'=>'Debe ser lider de grupo para realizar esta operacion');
                }
            }
            else{
                $success = false;
                    $errorlist = array('Error'=>'Como encargado del grupo, usted no puede removerse solo de el.');
            }
        }
        else{
            $success = false;
            $errorlist = array('Error'=>'Un usuario siempre debe pertenecer a una congregación de Iglesia. Si desea removerlo obligatoriamente debe asociarlo a otra congregación de Iglesia.');
        }
        $data = array(
            'success'=>$success,
            'msj'=>$mensaje,
            'errors'=>$errorlist
            );
        $this->layout->printLike(json_encode($data),'json');
   }
   
   public function verifyRol(){
        $uid = $this->input->post('uid');
        $uid = explode('_',$uid);
        $this->load->model('rols_model');
        $this->load->model('tiporols_model');
        $rols_data = $this->rols_model->getByGrupoId($uid[0]);
        $role_data = $this->tiporols_model->getBynombrerol('lider');
        $role_data = $role_data[0]->TipoRolId;
        $role;
        
        $session_id = $this->session->userdata('id_usuario');
        $this->load->model("users_model");
        $user_data = $this->users_model->getByusername($session_id);
        $user_data = $user_data[0]->UserId;
        
        foreach($rols_data as $rd){
            if($rd->UserId == $user_data) $role = $rd->TipoRolId;  
        }
        
        if($role == $role_data ) {
            $data = array(
            "success" => true,
            "msg" => '',
            "errors" => ''
            );
            $this->layout->printLike(json_encode($data),'json');
        }
        else {
            $data = array(
            "success" => false,
            "msg" => '',
            "errors" => 'Debes ser lider para realizar esta accion'
            );
            $this->layout->printLike(json_encode($data),'json');
            
        }
       
   }
    
 }

